/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useCallback, useEffect, useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProCard from '@ant-design/pro-card';
import ProTable from '@ant-design/pro-table';
import DragTable from '@/components/DragTable';
import ProForm, { ProFormText, ProFormSelect } from '@ant-design/pro-form';
import KbDrawer from '@/components/_pages/Finance/components/KbAddressModal';
import { Button, Popconfirm, Cascader, message, Space } from 'antd';
import { getBondList, getChildrenArea, approveBondBackApply } from '@/services/YzBond';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import type { ProFormInstance } from '@ant-design/pro-form';
import type { yzBond } from './index.d';
import styles from './index.less';
import { useSelector } from 'umi';
import { ConnectState } from '@/models/connect';

interface RefusePopconfirmProps {
  id: number;
  title: string;
  status: string;
  children: JSX.Element;
  actionRef: any;
  oldstatus: string;
}

const RefusePopconfirm: React.FC<RefusePopconfirmProps> = ({
  id,
  title,
  status,
  children,
  actionRef,
  oldstatus,
}) => {
  const confirm = async () => {
    approveBondBackApply({ id, new_action_status: status, old_action_status: oldstatus }).then(
      (res) => {
        message.info(res.msg);
        actionRef.current?.reload();
      },
    );
  };
  return (
    <Popconfirm title={title} onConfirm={confirm} okText='确认'>
      {children}
    </Popconfirm>
  );
};

const YzBond: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const { winSize } = useSelector((state: ConnectState) => state.global);

  const secrchOptionType = [
    { label: '交保证金', value: '1' },
    { label: '退保证金', value: '2' },
    { label: '罚款', value: '3' },
  ];
  const secrchOptionStatus = [
    {
      label: '待审核',
      value: '1',
    },
    {
      label: '运营审核同意',
      value: '2',
    },
    {
      label: '运营审核驳回',
      value: '3',
    },
    {
      label: '财务审核同意',
      value: '4',
    },
    {
      label: '财务审核驳回',
      value: '5',
    },
  ];
  const [addressList, setAddressList] = useState([]);
  const [submitting, setSubmitting] = useState(false);
  const [searchData, setSearchData] = useState({});
  const [options, setOptions] = useState([]);
  const [visible, setVisible] = useState<boolean>(false);
  const columns: ProColumns<yzBond>[] = [
    {
      title: '驿站id',
      dataIndex: 'cm_id',
      align: 'center',
      search: false,
    },
    {
      title: '驿站名称',
      dataIndex: 'inn_name',
      align: 'center',
      search: false,
    },
    {
      title: '驿站手机号',
      dataIndex: 'phone',
      align: 'center',
      search: false,
    },
    {
      title: '驿站区域',
      dataIndex: 'yz_address',
      align: 'center',
      search: false,
    },
    {
      title: '交易金额',
      dataIndex: 'trans_amount',
      align: 'center',
      search: false,
    },
    {
      title: '余额',
      dataIndex: 'balance',
      align: 'center',
      search: false,
    },
    {
      title: '操作时间',
      dataIndex: 'created_at',
      align: 'center',
      search: false,
    },
    {
      title: '类型',
      dataIndex: 'action_type',
      align: 'center',
      search: false,
    },
    {
      title: '状态',
      dataIndex: 'action_status',
      align: 'center',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'review_type',
      align: 'center',
      search: false,
      fixed: 'right',
      width: winSize === 'xs' ? 100 : 160,
      render: (_, record) => (
        <Space direction={winSize === 'xs' ? 'vertical' : 'horizontal'}>
          {record.action_status_code === '1' ? (
            <>
              <RefusePopconfirm
                key={`${record.cm_id}1`}
                id={record.id}
                title='确认同意？'
                oldstatus={record.action_status_code}
                status='2'
                actionRef={actionRef}
              >
                <Button type='primary' size='small' danger>
                  运营同意
                </Button>
              </RefusePopconfirm>
              <RefusePopconfirm
                key={`${record.cm_id}2`}
                id={record.id}
                title='确认驳回？'
                oldstatus={record.action_status_code}
                status='3'
                actionRef={actionRef}
              >
                <a>运营驳回</a>
              </RefusePopconfirm>
            </>
          ) : record.action_status_code === '2' ? (
            <>
              <RefusePopconfirm
                key={`${record.cm_id}3`}
                id={record.id}
                title='确认同意？'
                oldstatus={record.action_status_code}
                status='4'
                actionRef={actionRef}
              >
                <Button type='primary' size='small' danger>
                  财务同意
                </Button>
              </RefusePopconfirm>
              <RefusePopconfirm
                key={`${record.cm_id}4`}
                id={record.id}
                title='确认驳回？'
                oldstatus={record.action_status_code}
                status='5'
                actionRef={actionRef}
              >
                <a>财务驳回</a>
              </RefusePopconfirm>
            </>
          ) : null}
        </Space>
      ),
    },
  ];

  const fetchTableList = (params: any, data: any) => {
    const { current: page, pageSize, ...rest } = params;
    return getBondList({
      page,
      pageSize,
      ...rest,
      ...data,
    });
  };

  const exportExcel = (addressList_: any) => {
    const {
      action_type = '',
      action_status = '',
      keyword = '',
    } = formRef.current?.getFieldsValue();
    getBondList({
      action_type,
      action_status,
      keyword,
      area: JSON.stringify(addressList_),
      export: '1',
    });
  };

  const tableReload = (cb: () => void) => {
    const { reset } = actionRef.current || {};
    actionRef.current?.reload(false);
    if (reset) {
      reset();
    }
    if (typeof cb === 'function') {
      cb();
    }
  };

  const handleOption = () => setVisible(true);

  const onSubmit = async (values: any, addressList_: any) => {
    setSubmitting(true);
    setSearchData({ ...values, area: JSON.stringify(addressList_) });
    tableReload(() => {
      setSubmitting(false);
    });
  };

  const getAddress = useCallback(async (params) => {
    getChildrenArea(params).then((data) => {
      setOptions(data);
    });
  }, []);

  const onChange = useCallback((_, selectedOptions) => {
    const addressList_ = selectedOptions ? selectedOptions.map((item: any) => item.code) : [];
    setAddressList(addressList_);
  }, []);

  const loadData = (selectedOptions: any) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;
    const isLeaf = selectedOptions.length > 2;
    getChildrenArea({ id: targetOption.value }, isLeaf).then((data) => {
      targetOption.loading = false;
      targetOption.children = data;
      setOptions([...options]);
    });
  };

  useEffect(() => {
    getAddress({ id: '0' });
  }, []);

  return (
    <PageContainer className={styles.main} title='保证金管理'>
      <ProCard extra={<a onClick={handleOption}>区域设置</a>}>
        <ProForm
          formRef={formRef}
          layout={winSize === 'xs' ? 'vertical' : 'inline'}
          onFinish={(values) => onSubmit(values, addressList)}
          submitter={{
            render: (props) => {
              return (
                <Space size='middle'>
                  <Button
                    loading={submitting}
                    type='primary'
                    key='submit'
                    onClick={() => props.form?.submit?.()}
                  >
                    查询
                  </Button>
                  <Button
                    loading={submitting}
                    type='primary'
                    ghost
                    key='excel'
                    onClick={() => exportExcel(addressList)}
                  >
                    导出
                  </Button>
                </Space>
              );
            },
          }}
        >
          <ProFormSelect
            options={secrchOptionType}
            width='sm'
            name='action_type'
            placeholder='全部类型'
          />
          <ProForm.Item style={{ width: 216 }}>
            <Cascader
              options={options}
              loadData={loadData}
              onChange={onChange}
              changeOnSelect
              placeholder='全部区域'
            />
          </ProForm.Item>
          <ProFormSelect
            options={secrchOptionStatus}
            width='sm'
            name='action_status'
            placeholder='全部状态'
          />
          <ProFormText width='sm' name='keyword' placeholder='请输入驿站id/手机号/名称' />
        </ProForm>

        <DragTable>
          <ProTable<yzBond>
            actionRef={actionRef}
            pagination={{
              pageSize: 20,
              showQuickJumper: false,
              showSizeChanger: false,
            }}
            scroll={{ x: 1300 }}
            rowKey='id'
            request={(values) => fetchTableList(values, searchData)}
            columns={columns}
            search={false}
            options={false}
          />
        </DragTable>
        <KbDrawer visible={visible} onClose={setVisible}></KbDrawer>
      </ProCard>
    </PageContainer>
  );
};

export default YzBond;
